import { ref, reactive } from 'vue'
import { defineStore } from 'pinia';
import { api } from "@/services/api";
import { MenuItem } from '@/services/type'

export const useMenuStore = defineStore('menu', () => {
    // 菜单数据
    const menuData = reactive<MenuItem[]>([]); 
    // 当前选中下标
    const activeIndex = ref(1);
    // 获取当前路径
    const path = ref(window.location.pathname);
    // 当前菜单信息
    const currentMenu = ref({});

    /**
     * 获取菜单信息
     */
    const getMenuList = async () => {
        // 获取菜单信息
        const response = await api.common.getMenuList();
        // 如果状态返回成功
        if(response.code === 0) {
            // 获取菜单数据的下标
            const index: number = response.data.findIndex((item: MenuItem) => item.menu_url === path.value);
            if(index) {
                activeIndex.value = index + 1;
                currentMenu.value = response.data[index];
            } else {
                activeIndex.value = -1;
            }
            // 菜单数据赋值
            menuData.push(...response.data);
        }
    }; 
    return { menuData, activeIndex, currentMenu, getMenuList }
});